package com.csw.android.androidtest.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import com.csw.android.androidtest.R;
import com.csw.android.androidtest.app.MyApplication;
import com.csw.android.dev_utils.utils.RxBus;

/**
 * 前台服务，不知在哪个版本，android开始整治后台服务乱象，对后台服务功能与性能进行限制，但有些功能确实需要后台
 * 稳定运行的，于是前台服务诞生了，前台服务的使用与后台服务基本相同，只是多了个通知，前台服务必须在创建后五秒内
 * 显示一个通知在用户的通知栏，告知这里有个服务在运行，用户知道，那就是可见、前台的。。。于是现在前台服务成了主
 * 流，如播放器，安全软件，计步器等等。
 * <p>
 * 代码与startService基本一致
 */
public class ForegroundService extends Service {

    private static final String NOTIFICATION_CHANNEL_ID = "ForegroundService 通知渠道 id";
    private static final String NOTIFICATION_CHANNEL_NAME = "ForegroundService 前台服务测试通知渠道";
    private static final int NOTICE_ID = 81192;
    private static final String COMMAND_1 = "COMMAND_1";
    private static final String COMMAND_2 = "COMMAND_2";
    private static final String COMMAND_STOP = "COMMAND_STOP";

    public static void command1(String data) {
        Bundle d = new Bundle();
        d.putString("data", data);
        start(COMMAND_1, d);
    }

    public static void command2() {
        start(COMMAND_2, null);
    }

    public static void stop() {
        start(COMMAND_STOP, null);
    }

    public static void start(String command, Bundle data) {
        Intent intent = new Intent(MyApplication.instance, ForegroundService.class);
        intent.setAction(command);
        if (data != null) {
            intent.putExtras(data);
        }
        //以前台服务的方式启动服务，旧版本没有前台服务，所以使用兼容包的方法，内部对不同版本分开处理
        ContextCompat.startForegroundService(MyApplication.instance, intent);
    }

    //----------------------------------------------------------------------------------------------
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("AndroidTest")
            .setContentText("ForegroundServiceTest")
            .setOnlyAlertOnce(true);

    @Override
    public void onCreate() {
        super.onCreate();
        //状态初始化
        createNotificationChannelIfNotExist();
        Notification notification = notificationBuilder.build();
        NotificationManagerCompat.from(this).notify(NOTICE_ID, notification);
        //启动服务后需要调用这个方法告知系统此服务进入前台状态,否则RemoteServiceException
        startForeground(NOTICE_ID, notification);

        RxBus.Companion.getDefault().post(new StartService.OnCommandResult("ForegroundService created"));
    }

    private void createNotificationChannelIfNotExist() {
        //API 26以上创建通知需要划分通知渠道，以便用户可以控制app哪些渠道的通知可以关闭，比如单独屏蔽广告推送
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
            NotificationChannel nc = notificationManagerCompat.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
            if (nc == null) {
                nc = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationManagerCompat.createNotificationChannel(nc);
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            final String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case COMMAND_1:
                        String data = intent.getStringExtra("data");
                        execCommand1(data);
                        break;
                    case COMMAND_2:
                        execCommand2();
                        break;
                    case COMMAND_STOP:
                        stopSelf();
                        break;
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void execCommand1(String data) {
        String responseData = "ForegroundService is receive " + data;
        NotificationManagerCompat.from(this).notify(NOTICE_ID, notificationBuilder.setContentText(responseData).build());
        RxBus.Companion.getDefault().post(new OnCommandResult(responseData));
    }

    private void execCommand2() {
        String responseData = "ForegroundService execCommand2";
        NotificationManagerCompat.from(this).notify(NOTICE_ID, notificationBuilder.setContentText(responseData).build());
        RxBus.Companion.getDefault().post(new OnCommandResult(responseData));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        //服务若因为资源不足被关闭时，这里可以保存状态，等候下次启动时恢复。
        //关闭前台状态
        stopForeground(true);
        super.onDestroy();
    }

    //----------------------------------------------------------------------------------------------
    public static final class OnCommandResult {
        private final String data;

        public OnCommandResult(String data) {
            this.data = data;
        }

        public String getData() {
            return data;
        }
    }

}
